//要配置url
let BASE_URL
//请求超时
const TIME_OUT = 5000;
// #ifdef H5
BASE_URL = ''
// #endif
// #ifndef H5
BASE_URL = 'https://ai.xuexiluxian.cn'
// #endif
import store from '@/store'
//请求拦截器
const requestIntercepted = (config) => {
	let user = store.state?.user;
	let token = user?.token;
	if (token) {
		config.header['Authorization'] = token;
	}
	return config;
}

//响应拦截器
const responseIntercepted = (response) => {
	//比如：状态码等于 401，代表token过期
	return response;
}

export default {
	request(options) {
		return new Promise((resolve, reject) => {
			const finalOptions = {
				...options,
				url: BASE_URL ? BASE_URL + options.url : options.url,
				timeout: TIME_OUT,
				header: {
					'content-type': 'application/json',
					...options.header
				}
			}
			//请求拦截器
			const interceptedOptions = requestIntercepted(finalOptions);

			const requestTask = uni.request({
				...interceptedOptions,
				success: (response) => {
					//使用==》响应拦截器
					let res = responseIntercepted(response);
					if (res.statusCode >= 200 && res.statusCode < 300) {
						resolve(res.data);
					} else {
						reject(res);
					}
				}
			})
		})
	},
	post(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'post',
			...options
		})
	},
	get(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'get',
			...options
		})
	}
}